package com.video.netty.InChannelHandler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.video.entity.ClientMsg;
import com.video.service.client.IClientService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * golang返回的终端列表获取终端的状态
 *
 * 成功
 * {"id":"terminalStatusResponse","response":"success",
 *      "users":[
 *          {"id":"1","online":"1"},
 *          {"id":"2","online":"1"},
 *          {"id":"3","online":"0"}
 *       ]
 * }
 * 失败
 * {"id":"terminalStatusResponse","response":"fail"}
 *
 */
@BaseChannelHandler.MsgHandler
public class WsTerminalStatusResponseChannelHandler extends BaseChannelHandler {

    @Autowired
    private IClientService clientService;

    @Override
    protected String msgId() {
        return "terminalStatusResponse";
    }

    @Override
    protected void msgHandler(JSONObject json) {
        //同步终端状态
        JSONArray users = json.getJSONArray("users");

        if(users != null){
            for (int i = 0; i < users.size(); i++){
                JSONObject jsonObject1 = users.getJSONObject(i);

                ClientMsg cmsg = clientService.getById(jsonObject1.getInteger("id"));
                cmsg.setId(jsonObject1.getInteger("online") == 1 ? "online" : "offline");
                cmsg.setStatus(jsonObject1.getInteger("online"));
                clientService.insertOrUpdate(cmsg);
            }
        }
    }
}
